package com.fsj.miniapp.shiro;

import com.fsj.miniapp.caches.UserCache;
import com.fsj.miniapp.model.User;
import com.fsj.miniapp.service.FunctionConfigService;
import com.fsj.miniapp.service.PermService;
import com.fsj.miniapp.service.RoleService;
import com.fsj.miniapp.service.UserService;
import com.fsj.miniapp.vo.FunctionVo;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;
import java.util.stream.Collectors;

public class CustomRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private PermService permService;

    @Autowired
    private FunctionConfigService functionConfigService;

    //告诉shiro如何根据获取到的用户信息中的密码和盐值来校验密码
    {
        //设置用于匹配密码的CredentialsMatcher
        CredentialMatcher credentialMatcher = new CredentialMatcher();
        this.setCredentialsMatcher(credentialMatcher);
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //null usernames are invalid
        if (principals == null) {
            throw new AuthorizationException("PrincipalCollection method argument cannot be null.");
        }

        User user = (User) getAvailablePrincipal(principals);

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setRoles(user.getRoles());
        info.setStringPermissions(user.getPerms());
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken upToken = (UsernamePasswordToken) token;
        String username = upToken.getUsername();

        // Null username is invalid
        if (username == null) {
            throw new AccountException("Null usernames are not allowed by this realm.");
        }

        User userDB = userService.findUserByName(username);


        if (userDB == null) {
            throw new UnknownAccountException("No account found for admin [" + username + "]");
        }

        //查询用户的角色和权限存到SimpleAuthenticationInfo中，这样在其它地方
        //SecurityUtils.getSubject().getPrincipal()就能拿出用户的所有信息，包括角色和权限
        Set<String> roles = roleService.getRolesByUserId(userDB.getId());
        Set<FunctionVo> functionVos = functionConfigService.findAllFuncsByUserId(userDB.getId()).stream().map(f -> {
            FunctionVo vo = new FunctionVo();
            BeanUtils.copyProperties(f, vo);
            return vo;
        }).collect(Collectors.toSet());
        Set<String> perms = functionVos.stream().map(f -> f.getName()).collect(Collectors.toSet());
        userDB.getRoles().addAll(roles);
        userDB.getPerms().addAll(perms);

        userDB.getFuncs().addAll(functionVos);
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(userDB, userDB.getPassword(), getName());
        if (userDB.getSalt() != null) {
            info.setCredentialsSalt(ByteSource.Util.bytes(userDB.getSalt()));
        }

        UserCache.setFuncs(userDB.getId(), userDB.getPerms());

        return info;
    }
}
